package com.tracesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tracesystem.commons.Result;
import com.tracesystem.controller.info.IssueProjectInfo;
import com.tracesystem.controller.form.*;
import com.tracesystem.controller.info.ProjectPageUserInfo;
import com.tracesystem.controller.info.SimpleUserInfo;
import com.tracesystem.dao.IssueProjectRoleRelDao;
import com.tracesystem.dao.IssueRoleDao;
import com.tracesystem.dao.IssueUserDao;
import com.tracesystem.model.InfoIssueProject;
import com.tracesystem.dao.InfoIssueProjectDao;
import com.tracesystem.model.IssueProjectRoleRel;
import com.tracesystem.model.IssueRole;
import com.tracesystem.model.IssueUser;
import com.tracesystem.service.InfoIssueProjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tracesystem.util.WoniuCopyUtil;
import com.tracesystem.util.exception.IssueProjectException;
import com.tracesystem.util.exception.ParameterErrorExpression;
import com.tracesystem.util.exception.ProjectRoleRelException;
import com.tracesystem.util.exception.code.IssueProjectExceptionCode;
import com.tracesystem.util.exception.code.IssueProjectRoleRelExceptionCode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Kevin Martin
 * @since 2022-03-23
 */
@Service
public class InfoIssueProjectServiceImpl extends ServiceImpl<InfoIssueProjectDao, InfoIssueProject> implements InfoIssueProjectService {
    @Resource
    private IssueProjectRoleRelDao issueProjectRoleRelDao;
    @Resource
    private IssueUserDao issueUserDao;
    @Resource
    private IssueRoleDao roleDao;
    @Resource
    private InfoIssueProjectDao projectDao;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result closeProject(CloseProjectForm closeProjectForm) {
        InfoIssueProject infoIssueProject = WoniuCopyUtil.copyOne(closeProjectForm, InfoIssueProject.class);
        infoIssueProject.setProjectState("关闭");
        updateById(infoIssueProject);
        return Result.getInstance().setMsg("修改成功");
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result enableProject(OpenProjectForm openProjectForm) {
        InfoIssueProject infoIssueProject = WoniuCopyUtil.copyOne(openProjectForm, InfoIssueProject.class);
        infoIssueProject.setProjectState("有效");
        updateById(infoIssueProject);
        return Result.getInstance().setMsg("修改成功");
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> addProject(NewProjectForm newProjectForm) {
        InfoIssueProject entity = WoniuCopyUtil.copyOne(newProjectForm, InfoIssueProject.class);
        entity.setProjectState("有效");
        save(entity);
        return Result.getInstance().setMsg("添加项目成功");
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result<?> changeProject(ChangeProjectForm changeProjectForm) {
        InfoIssueProject infoIssueProject = getById(changeProjectForm.getProjectId());
        QueryWrapper<InfoIssueProject> updateWrapper = new QueryWrapper<>();
        boolean flag1=false;
        boolean flag2 = false;
        if (null==changeProjectForm.getProjectIntro()||""==changeProjectForm.getProjectIntro().trim()) {
        }else {
            flag1=true;
            infoIssueProject.setProjectIntro(changeProjectForm.getProjectIntro());
        }
        if(null!=changeProjectForm.getProjectDesc()&&""!=changeProjectForm.getProjectDesc().trim()){
            flag1=true;
            infoIssueProject.setProjectDesc(changeProjectForm.getProjectDesc());
        }
        //两个参数都为空值抛出参数异常
        if(flag1==false&&flag2==false){
            throw new ParameterErrorExpression("不能修改为空");
        }
        infoIssueProject.setModifyBy(changeProjectForm.getModifyBy());
        boolean b = updateById(infoIssueProject);
        if(b){
            return Result.getInstance().setMsg("修改成功");
        }else {
            throw new IssueProjectException(IssueProjectExceptionCode.PROJECT_UPDATEEXCEPTION_CODE);
        }


    }

    @Override
    public Result<Page<IssueProjectInfo>> getProjectPageinfor(ProjectPageForm projectPageForm) {
        QueryWrapper<InfoIssueProject> queryWrapper =null;
            //查询两个字段中符合模糊条件的数据
            if(projectPageForm.getProjectKey()!=null&&projectPageForm.getProjectKey().trim()!=""){
                queryWrapper=new QueryWrapper<>();
                queryWrapper.like("PROJECT_NAME",projectPageForm.getProjectKey()).or().like("PROJECT_ID",projectPageForm.getProjectKey());
            }
        Page<InfoIssueProject> page = page(new Page<>(projectPageForm.getPageIndex(), projectPageForm.getPageSize()), queryWrapper);
        List<InfoIssueProject> records = page.getRecords();
        List<IssueProjectInfo> issueProjectInfos = WoniuCopyUtil.copyMany(records, IssueProjectInfo.class);
        Page<IssueProjectInfo> issueProjectInfoPage = new Page<>();
        issueProjectInfoPage.setRecords(issueProjectInfos)
                .setPages(page.getPages())
                .setCurrent(page.getCurrent())
                .setTotal(page.getTotal())
                .setSize(page.getSize());
        return Result.getInstance(Page.class).setData(issueProjectInfoPage).setMsg("查询成功");
    }

    @Override
    public Result<?> doProjectBindRole(ProjectBindRoleForm projectBindRoleForm) {
        List<IssueUser> issueUsers = issueUserDao.selectBatchIds(projectBindRoleForm.getUserIds());
        if (null == issueUsers || issueUsers.size() != projectBindRoleForm.getUserIds().size()) {
            throw new ProjectRoleRelException(IssueProjectRoleRelExceptionCode.ISSUEPROJECTROLEREL_USERNOTEXIST_ERROR);
        }
        InfoIssueProject infoIssueProject = projectDao.selectById(projectBindRoleForm.getProjectId());
        System.out.println(projectBindRoleForm);
        if (null == infoIssueProject) {
            throw new ProjectRoleRelException(IssueProjectRoleRelExceptionCode.ISSUEPROJECTROLEREL_NOPROJECT_ERROR);
        }
        IssueRole issueRole = roleDao.selectById(projectBindRoleForm.getRoleId());
        if (null == issueRole || "禁用".equals(issueRole.getModuleState())) {
            throw new ProjectRoleRelException(IssueProjectRoleRelExceptionCode.ISSUEPROJECTROLEREL_NOROLEEXIST_ERROR);
        }
        Iterator<IssueUser> iterator = issueUsers.iterator();
        while (iterator.hasNext()) {
            IssueUser next = iterator.next();
            next.setRoleId(projectBindRoleForm.getRoleId());
            issueUserDao.updateById(next);
            IssueProjectRoleRel issueProjectRoleRel1 = new IssueProjectRoleRel();
            issueProjectRoleRel1.setProjectId(projectBindRoleForm.getProjectId());
            issueProjectRoleRel1.setRoleId(projectBindRoleForm.getRoleId());
            issueProjectRoleRel1.setUserId(next.getUserId());
            issueProjectRoleRelDao.insert(issueProjectRoleRel1);
        }
//        int i = issueUserDao.(issueUser);
//        int insert = issueProjectRoleRelDao.insert(WoniuCopyUtil.copyOne(projectBindRoleForm, IssueProjectRoleRel.class));
        return Result.getInstance().setMsg("添加成功");
    }

    @Override
    public Result<List<SimpleUserInfo>> getListUserByRole() {
        List<IssueUser> emptyRoleIdUsers = issueUserDao.selectList(new QueryWrapper<IssueUser>().isNull("ROLE_ID"));
        if (null == emptyRoleIdUsers || emptyRoleIdUsers.size() == 0) {
            throw new ProjectRoleRelException(IssueProjectRoleRelExceptionCode.ISSUEPROJECTROLEREL_NOIDLEUSER_ERROR);
        }
        return Result.getInstance().setMsg("查询成功").setData(emptyRoleIdUsers);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result cutMember(RMMemberByUid rmMemberByUid) {
        IssueUser issueUser = issueUserDao.selectById(rmMemberByUid.getUserId());
        if (null == issueUser) {
            throw new ProjectRoleRelException(IssueProjectRoleRelExceptionCode.ISSUEPROJECTROLEREL_USERNOTEXIST_ERROR);
        }
        issueUser.setRoleId(null);
        System.out.println(issueUser);
        issueUserDao.updateById(issueUser);
        issueProjectRoleRelDao.delete(new QueryWrapper<IssueProjectRoleRel>().
                eq("PROJECT_ID", rmMemberByUid.getProjectId()).eq("USER_ID", rmMemberByUid.getUserId()));
        return Result.getInstance().setMsg("移除成功");
    }

    @Override
    public Result<Page<ProjectPageUserInfo>> findPageProjectUsers(PorjectPageUserForm porjectPageUserForm) {
        Page<ProjectPageUserInfo> projectPageUserInfoPage = new Page<ProjectPageUserInfo>
                (porjectPageUserForm.getPageIndex(), porjectPageUserForm.getPageSize());
        List<ProjectPageUserInfo> users = issueProjectRoleRelDao.seleListProjectUsers
                (projectPageUserInfoPage, porjectPageUserForm.getProjectId(), porjectPageUserForm.getNameKey());
//        ArrayList<ProjectPageUserInfo> projectPageUserInfos = new ArrayList<>();
//        for (ProjectPageUserInfo user : users) {
//            projectPageUserInfos.add(user);
//        }
//        int bignum=0;
//        if(porjectPageUserForm.getPageIndex() * porjectPageUserForm.getPageSize() - 1>projectPageUserInfos.size()){
//            bignum=projectPageUserInfos.size();
//        }else  bignum=porjectPageUserForm.getPageIndex() * porjectPageUserForm.getPageSize() - 1;
//
//        List<ProjectPageUserInfo> projectPageUserInfos1 = projectPageUserInfos.subList(
//                (porjectPageUserForm.getPageIndex() - 1) * porjectPageUserForm.getPageSize(),
//                bignum
//        );
//        projectPageUserInfoPage.setRecords(projectPageUserInfos1);
        projectPageUserInfoPage.setRecords(users);
        return Result.getInstance(Page.class).setData(projectPageUserInfoPage);
    }


}
